//
//  ZKSegmentControl.m
//  朱凯的工具箱
//
//  Created by pro on 17/2/25.
//  Copyright © 2017年 zhukai. All rights reserved.
//

#import "ZKSegmentControl.h"

static CGFloat kSegmentTitleMargin = 20;

@interface ZKSegmentControl () <UIScrollViewDelegate>

@property (nonatomic, strong) UIScrollView  *segmentScroll;  // 分段滑动视图
@property (nonatomic, strong) UIScrollView  *contentScroll;  // 内容滑动视图
@property (nonatomic, strong) UIView        *selectedView;   // 选中视图

@property (nonatomic, assign) NSInteger     preTag;          // 当前选中

@end

@implementation ZKSegmentControl

#pragma mark - 初始化
// 初始化方法
- (instancetype)init {
    
    if (self = [super init]) {
        
        [self setupUI];
    }
    return self;
}

#pragma mark - 懒加载
// 分段滑动视图
- (UIScrollView *)segmentScroll {
    
    if (!_segmentScroll) {
        _segmentScroll = [[UIScrollView alloc] init];
        _segmentScroll.showsVerticalScrollIndicator = NO;
        _segmentScroll.showsHorizontalScrollIndicator = NO;
    }
    return _segmentScroll;
}
// 内容滑动视图
- (UIScrollView *)contentScroll {
    
    if (!_contentScroll) {
        _contentScroll = [[UIScrollView alloc] init];
        _contentScroll.showsVerticalScrollIndicator = NO;
        _contentScroll.showsHorizontalScrollIndicator = NO;
        _contentScroll.delegate = self;
        _contentScroll.pagingEnabled = YES;
    }
    return _contentScroll;
}
// 选中视图
- (UIView *)selectedView {
    
    if (!_selectedView) {
        _selectedView = [[UIView alloc] init];
        _selectedView.backgroundColor = self.segmentSelectTint;
        [self.segmentScroll addSubview:_selectedView];
    }
    return _selectedView;
}
// segment高度
- (NSNumber *)segmentHeight {
    
    if (!_segmentHeight) {
        _segmentHeight = @(44);
    }
    return _segmentHeight;
}
// segment选中视图的高度
- (NSNumber *)segmentSelectedViewHeight {
    
    if (!_segmentSelectedViewHeight) {
        _segmentSelectedViewHeight = @(2);
    }
    return _segmentSelectedViewHeight;
}
// segment最多标题数，超出则可滑动
- (NSNumber *)segmentMaxTitles {
    
    if (!_segmentMaxTitles) {
        _segmentMaxTitles = @(4);
    }
    return _segmentMaxTitles;
}
// segment宽度是否自适应
- (NSNumber *)segmentTitleWidthDynamically {
    
    if (!_segmentTitleWidthDynamically) {
        _segmentTitleWidthDynamically = @(NO);
    }
    return _segmentTitleWidthDynamically;
}
// segment标题字体大小
- (NSNumber *)segmentTitleFontSize {
    
    if (!_segmentTitleFontSize) {
        _segmentTitleFontSize = @(16);
    }
    return _segmentTitleFontSize;
}
// segment背景颜色
- (UIColor *)segmentBackgroundTint {
    
    if (!_segmentBackgroundTint) {
        _segmentBackgroundTint = [UIColor whiteColor];
    }
    return _segmentBackgroundTint;
}
// segment未选中颜色
- (UIColor *)segmentNormalTint {
    
    if (!_segmentNormalTint) {
        _segmentNormalTint = [UIColor blackColor];
    }
    return _segmentNormalTint;
}
// segment选中颜色
- (UIColor *)segmentSelectTint {
    
    if (!_segmentSelectTint) {
        _segmentSelectTint = [UIColor redColor];
    }
    return _segmentSelectTint;
}
#pragma mark - 设置属性
// 设置标题数组
- (void)setSegmentsArray:(NSArray *)segmentsArray {
    
    if (_segmentsArray != segmentsArray) {
        _segmentsArray = segmentsArray;
    }
    [self.segmentScroll mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(self.segmentHeight);
    }];
    [self performSelector:@selector(layoutSegmentScroll) withObject:nil afterDelay:0.001];
}
// 动态添加内容视图
- (void)setDynamicalAddContentViewBlock:(void (^)(void (^)(ZKSegmentContentView *), NSInteger))dynamicalAddContentViewBlock {
    
    _dynamicalAddContentViewBlock = dynamicalAddContentViewBlock;
    
    [self performSelector:@selector(layoutContentScroll) withObject:nil afterDelay:0.001];
}


#pragma mark - 布局视图
// 设置基本UI
- (void)setupUI {
    
    // 添加两个滑动子视图
    [self addSubview:self.segmentScroll];
    [self addSubview:self.contentScroll];

    // 线条
    UIView *line = [UIView new];
    line.backgroundColor = [UIColor colorWithWhite:0.85 alpha:1];
    [self addSubview:line];

    
    // 自动布局
    [self.segmentScroll mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self);
        make.height.equalTo(self.segmentHeight);
    }];
    
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self);
        make.top.equalTo(self.segmentScroll.mas_bottom);
        make.height.equalTo(@1);
    }];
    
    [self.contentScroll mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self);
        make.top.equalTo(line.mas_bottom);
    }];
}
- (void)layoutSegmentScroll {
    
    // 对segment数组断言
    NSAssert(self.segmentsArray.count && self.segmentsArray, @"标题数组不能为空");
    
    // 先移除子视图
    [self.segmentScroll.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    // 设置segmentScroll的背景颜色
    self.segmentScroll.backgroundColor = self.segmentBackgroundTint;
    
    // 宽度非自适应的情况下布局视图
    if (!self.segmentTitleWidthDynamically.boolValue) {
        int visableCount = (int)MIN(self.segmentMaxTitles.intValue, self.segmentsArray.count);

        __block CGFloat x, y, width, height;
        x = 0;
        y = 0;
        width = self.segmentScroll.width / visableCount;
        height = self.segmentScroll.height;
        [self.segmentsArray enumerateObjectsUsingBlock:^(NSString *title, NSUInteger index, BOOL * _Nonnull stop) {
            
            x = index * width;
            
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.titleLabel.font = FONT(self.segmentTitleFontSize.floatValue);
            [button setFrame:CGRectMake(x, y, width, height)];
            [button setTitle:title forState:UIControlStateNormal];
            [button setTitleColor:self.segmentNormalTint forState:UIControlStateNormal];
            [button setTitleColor:self.segmentSelectTint forState:UIControlStateSelected];
            [button addTarget:self action:@selector(segmentTitleTap:) forControlEvents:UIControlEventTouchUpInside];
            [self.segmentScroll addSubview:button];
            button.tag = index;
        }];
        
    }
    // 宽度自适应的情况下布局视图
    else {
        __block CGFloat x, y, width, height;
        x = 0;
        y = 0;
        height = self.segmentScroll.height;
        
        [self.segmentsArray enumerateObjectsUsingBlock:^(NSString *title, NSUInteger index, BOOL * _Nonnull stop) {
            
            width = [title getSizeOfString:self.segmentTitleFontSize.floatValue].width + kSegmentTitleMargin;
            
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.titleLabel.font = FONT(self.segmentTitleFontSize.floatValue);
            [button setFrame:CGRectMake(x, y, width, height)];
            [button setTitle:title forState:UIControlStateNormal];
            [button setTitleColor:self.segmentNormalTint forState:UIControlStateNormal];
            [button setTitleColor:self.segmentSelectTint forState:UIControlStateSelected];
            [button addTarget:self action:@selector(segmentTitleTap:) forControlEvents:UIControlEventTouchUpInside];
            [self.segmentScroll addSubview:button];
            button.tag = index;
            
            // 设置x偏移
            x += width;
        }];
    }
    
    // 刚创建好默认设置第一个按钮为选中
    UIButton *firstButton = self.segmentScroll.subviews.firstObject;
    firstButton.selected = YES;
    // 调整选中视图的位置
    [self adjustSelectedViewFrame:firstButton animated:NO];
    self.preTag = firstButton.tag;
    
    // 设置segmentScroll的滑动范围
    UIButton *lastButton = [self.segmentScroll viewWithTag:self.segmentsArray.count - 1];
    self.segmentScroll.contentSize = CGSizeMake(lastButton.right, 0);
    
    
}
- (void)layoutContentScroll {
    
    // 初始化内容添加数组
    self.contentAddedViews = [[NSMutableArray alloc] initWithCapacity:self.segmentsArray.count];
    for (int i = 0; i < self.segmentsArray.count; i ++) {
        [self.contentAddedViews addObject:[NSNull null]];
    }
    
    // 先移除子视图
    [self.contentScroll.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    self.contentScroll.contentSize = CGSizeMake(self.contentScroll.width * self.contentAddedViews.count, self.contentScroll.height);
    
    // 默认添加第一个content
    [self dynamicalAddContentViewWithBlockAtIndex:0];
}


#pragma mark - 滑动视图 delegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    // 当滑动停下时，计算滑动到了index页
    NSInteger index = self.contentScroll.contentOffset.x / self.contentScroll.width;
    
    // 设置segment选中中的index
    [self adjustSegmentSelectedIndex:index];
}



#pragma mark - 点击事件
// segment标题点击事件
- (void)segmentTitleTap:(UIButton *)sender {
    
    // 点击了已经点击的按钮
    if (sender.selected == YES) {
        return;
    }
    
    // 回调
    if (self.titleTapBlock) {
        self.titleTapBlock(sender.tag);
    }
    
    // 设置segment选中中的index
    [self adjustSegmentSelectedIndex:sender.tag];
    self.preTag = sender.tag;
    
}

#pragma mark - 辅助方法
// 通过Block回调的方式动态添加内容视图
- (void)dynamicalAddContentViewWithBlockAtIndex:(NSInteger)index {
    
    if (self.dynamicalAddContentViewBlock) {
        
        BOOL isExistContentAtIndex = self.contentAddedViews[index] != [NSNull null];
        
        void (^contentViewFetchBlock)(ZKSegmentContentView *content) = ^ (ZKSegmentContentView *contentView) {
            
            if (isExistContentAtIndex) {
                
                ZKSegmentContentView *contentViewAtIndex = self.contentAddedViews[index];
                if (contentViewAtIndex.contentViewDidAppear) {
                    contentViewAtIndex.contentViewDidAppear(index);
                }
                
            } else {
                if (contentView.contentViewDidLoad) {
                    contentView.contentViewDidLoad(index);
                }
                if (contentView.contentViewDidAppear) {
                    contentView.contentViewDidAppear(index);
                }
                
                CGFloat x = index * self.contentScroll.width;
                CGFloat y = 0;
                CGFloat width = self.contentScroll.width;
                CGFloat height = self.contentScroll.height;
                contentView.frame = CGRectMake(x, y, width, height);
                [self.contentScroll addSubview:contentView];
                
                [self.contentAddedViews replaceObjectAtIndex:index withObject:contentView];
                
             
            }
        };
        
        self.dynamicalAddContentViewBlock(contentViewFetchBlock, index);
        
        [self.contentScroll setContentOffset:CGPointMake(self.contentScroll.width * index, 0) animated:YES];
    }
}

// 设置segment选中中的index
- (void)adjustSegmentSelectedIndex:(NSInteger)index {
    
    // 遍历segmentScroll，设置选中的button（同时设置选中视图的位置），并将其他button设置为不选中
    for (UIView *subview in self.segmentScroll.subviews) {
        if (subview.tag < self.segmentsArray.count && [subview isKindOfClass:[UIButton class]]) {
            if (index == subview.tag) {
                ((UIButton *)subview).selected = YES;
                [self adjustSelectedViewFrame:(UIButton *)subview animated:YES];
            } else {
                ((UIButton *)subview).selected = NO;
            }
        }
    }
    
    // 设置contentScroll滑动到某一个内容视图，并动态添加该视图
    if (self.dynamicalAddContentViewBlock) {
        [self dynamicalAddContentViewWithBlockAtIndex:index];
    }

}
// 设置选中视图的位置
- (void)adjustSelectedViewFrame:(UIButton *)relatedView animated:(BOOL)animated {
    
    [UIView animateWithDuration:animated ? 0.25:0 animations:^{
        CGFloat width = 0;
        // 如果标题宽度自适应了，则选中视图宽度一定也是自适应的
        if (self.segmentTitleWidthDynamically.boolValue) {
            width = [relatedView.titleLabel.text getSizeOfString:relatedView.titleLabel.font.pointSize].width + 5;
        }
        // 否则判断选中视图宽度是否自适应
        else {
            if (self.segmentSelectedViewWidthDynamically.boolValue) {
                width = [relatedView.titleLabel.text getSizeOfString:relatedView.titleLabel.font.pointSize].width + 5;
            } else {
                width = relatedView.width;
            }
        }
        
        [self.selectedView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(relatedView);
            make.bottom.equalTo(relatedView);
            make.height.equalTo(self.segmentSelectedViewHeight);
            make.width.equalTo(@(width));
        }];
    }];
    
    // 设置滑动视图显示为最中间
    [self adjustSegmentScrollVisableCenter:relatedView];
}
// 设置滑动视图显示为最中间
- (void)adjustSegmentScrollVisableCenter:(UIView *)selectedButton {
    
    // 滚动标题栏到中间位置
    CGFloat offsetx = selectedButton.x - self.segmentScroll.width * 0.5;
    CGFloat offsetMax = self.segmentScroll.contentSize.width - self.segmentScroll.width;
    
    // 在最左和最右时，标签没必要滚动到中间位置。
    if (self.segmentScroll.contentSize.width > self.segmentScroll.width) {
        if (offsetx < 0) {
            offsetx = 0;
        }
        if (offsetx > offsetMax) {
            offsetx = offsetMax;
        }
        [self.segmentScroll setContentOffset:CGPointMake(offsetx, 0) animated:YES];
    }
}
/*
 手动设置选择segment
 */
- (void)setSelectedSegment:(NSInteger)selectedSegment{
    NSLog(@"%ld--%ld",selectedSegment,self.preTag);
    // 如果是当前所需
    if (selectedSegment == self.preTag) {
        return;
    }
    
    // 遍历segmentScroll，设置选中的button（同时设置选中视图的位置），并将其他button设置为不选中
    for (UIView *subview in self.segmentScroll.subviews) {
        if (subview.tag < self.segmentsArray.count && [subview isKindOfClass:[UIButton class]]) {
            if (selectedSegment == subview.tag) {
                ((UIButton *)subview).selected = YES;
//                [self adjustSelectedViewFrame:(UIButton *)subview animated:YES];
            } else {
                ((UIButton *)subview).selected = NO;
            }
        }
    }
    
    // 回调
    if (self.titleTapBlock) {
        self.titleTapBlock(selectedSegment);
    }
    
    // 设置segment选中中的index
    [self adjustSegmentSelectedIndex:selectedSegment];
    
}
@end
